<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="120px">
    <!-- <el-form-item label="外键(音频主键)" prop="audioId">
      <el-input v-model="dataForm.audioId" placeholder="外键(音频主键)"></el-input>
    </el-form-item>
    <el-form-item label="音频code(冗余)" prop="audioCode">
      <el-input v-model="dataForm.audioCode" placeholder="音频code(冗余)"></el-input>
    </el-form-item> -->
    <!-- <el-form-item label="音频类型:" prop="showType">
      <el-select v-model="dataForm.showType" multiple>
        <el-option
          v-for="item in showTypeOptions"
          :key="item.id"
          :label="item.name"
          :value="item.id">
        </el-option>
      </el-select>
    </el-form-item> -->
    <el-form-item label="子项名称:" prop="itemName" style="width: 400px;">
      <el-input v-model="dataForm.itemName" placeholder="子项名称"></el-input>
    </el-form-item>
    <el-form-item label="序号" prop="orders" style="width: 400px;">
      <el-input v-model="dataForm.orders" placeholder="序号"></el-input>
    </el-form-item>
    <!-- <el-form-item label="封面图a-竖:" prop="coverImgA">
      <el-input v-model="dataForm.coverImgA" placeholder="封面图a-竖"></el-input>
    </el-form-item>
    <el-form-item label="封面图b-横:" prop="coverImgB">
      <el-input v-model="dataForm.coverImgB" placeholder="封面图b-横着"></el-input>
    </el-form-item>
    <el-form-item label="音频url:" prop="audioUrl">
      <el-input v-model="dataForm.audioUrl" placeholder="为音频故事时:音频url"></el-input>
    </el-form-item> -->
    <div class="item-wrapper"
           style="display: flex;flex-direction: row;margin-top: 30px;">
        <div class="item-pic-wrapper"
             style="margin-right: 150px;">
          <span style="color: #f56c6c;margin-right: 4px">*</span>封面图a-竖：
          <div style="font-size: 12px;margin-right: 6px;">限传一张图片,图片尺寸最佳为400X480像素</div>
          <div class="coverImg-wrapper pic">
            <el-upload ref="uploadCoverImg"
                       :action="uploadCoverImgUrl"
                       :before-upload="beforeCoverImgUpload"
                       :on-error="handleCoverImgError"
                       :on-success="handleCoverImgSuccess"
                       :show-file-list="showCoverImgUpload">
              <img v-if="dataForm.coverImgA"
                   class="coverImg"
                   :src="dataForm.coverImgA">
              <i v-else
                 class="el-icon-plus coverImg-uploader-icon"></i>
            </el-upload>
            <!--<span style="font-size: 12px;margin-left: 12px;margin-right: 6px;">限传一张图片,图片尺寸最佳为400X480像素</span>-->
          </div>
          <span class="error-tip">{{coverImgErrorTip}}</span>
        </div>
        <div class="item-pic-wrapper">
          <span> 封面图b-横：</span>
          <div style="font-size: 12px;margin-right: 6px;">限传一张轮播图,图片尺寸最佳为960X540像素</div>
          <div class="bannerImg-wrapper pic">
            <el-upload ref="uploadBannerImg"
                       :action="uploadBannerImgUrl"
                       :before-upload="beforeBannerImgUpload"
                       :on-error="handleBannerImgError"
                       :on-success="handleBannerImgSuccess"
                       :show-file-list="showBannerImgUpload">
              <img v-if="dataForm.coverImgB"
                   class="bannerImg"
                   :src="dataForm.coverImgB">
              <i v-else
                 class="el-icon-plus bannerImg-uploader-icon"></i>
            </el-upload>

          </div>
          <span class="error-tip">{{bannerImgErrorTip}}</span>
        </div>
      </div>
      <el-form-item label="音频文件"
                    prop="audioUrl"
                    style="width: 100%;margin-bottom: 30px;">
        <div style="display: flex;margin-bottom: 10px;">
          <el-tooltip effect="dark"
                      placement="top-start"
                      :content="dataForm.audioUrl ? dataForm.audioUrl : '请先上传音频文件'">
            <el-input disabled
                      v-model="dataForm.audioUrl" placeholder="音频文件的url"></el-input>
          </el-tooltip>
          <el-upload accept=".mp3, .m4a"
                     action=""
                     :before-upload="beforeUploadMp3"
                     :http-request="fnUploadRequest"
                     :on-error="handleUploadError"
                     :on-success="handleMp3Success"
                     :show-file-list="false">
            <el-button style="margin-left: 10px;"
                       type="primary">上传音频
            </el-button>
          </el-upload>
        </div>
        <el-progress v-if="progress > 0"
                     :percentage="progress"></el-progress>
      </el-form-item>
    <!-- （-1上传失败，0处理中，1上传成功） -->
    <!-- <el-form-item label="上传状态:" prop="uploadStatus">
      <el-radio v-model="dataForm.uploadStatus" :label="1">上传成功</el-radio>
      <el-radio v-model="dataForm.uploadStatus" :label="0">处理中</el-radio>
      <el-radio v-model="dataForm.uploadStatus" :label="-1">上传失败</el-radio>
    </el-form-item> -->
    <!-- (1上架,0下架,-1级联下架) -->
    <!-- <el-form-item label="上下架状态:" prop="status">
      <el-radio v-model="dataForm.status" :label="1">上架</el-radio>
      <el-radio v-model="dataForm.status" :label="0">下架</el-radio>
      <el-radio v-model="dataForm.status" :label="-1">级联下架</el-radio>
    </el-form-item>
    <el-form-item label="备注:" prop="remark">
      <el-input v-model="dataForm.remark" placeholder="备注" type="textarea" rows="2"></el-input>
    </el-form-item>
    <el-form-item label="p2位置图标:" prop="cornerIdP2" style="width: 400px;">
      <el-input v-model="dataForm.cornerIdP2" placeholder="p2位置图标"></el-input>
    </el-form-item>
    <el-form-item label="p3位置图标:" prop="cornerIdP3" style="width: 400px;">
      <el-input v-model="dataForm.cornerIdP3" placeholder="p3位置图标"></el-input>
    </el-form-item>
    <el-form-item label="p4位置图标:" prop="cornerIdP4" style="width: 400px;">
      <el-input v-model="dataForm.cornerIdP4" placeholder="p4位置图标"></el-input>
    </el-form-item> -->
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import oss from '../../../utils/aliOss'
  export default {
    data () {
      return {
        coverImgErrorTip: '',
        showCoverImgUpload: true,
        bannerImgErrorTip: '',
        showBannerImgUpload: true,
        progress: 0,
        uploadCoverImgUrl: this.$http.adornUrl(`/sys/oss/upload?token=${this.$cookie.get('token')}`),
        uploadBannerImgUrl: this.$http.adornUrl(`/sys/oss/upload?token=${this.$cookie.get('token')}`),
        visible: false,
        dataForm: {
          audioId: '',
          audioCode: '',
          showType: '',
          orders: '',
          itemName: '',
          coverImgA: '',
          coverImgB: '',
          audioUrl: '',
          uploadStatus: '',
          status: '',
          remark: '',
          cornerIdP2: '',
          cornerIdP3: '',
          cornerIdP4: ''
        },
        showTypeOptions: [],
        dataRule: {
          audioId: [
            { required: true, message: '外键(音频主键)不能为空', trigger: 'blur' }
          ],
          audioCode: [
            { required: true, message: '音频code(冗余)不能为空', trigger: 'blur' }
          ],
          showType: [
            { required: true, message: '音频类型不能为空', trigger: 'blur' }
          ],
          orders: [
            { required: true, message: '序号不能为空', trigger: 'blur' }
          ],
          itemName: [
            { required: true, message: '子项名称不能为空', trigger: 'blur' }
          ],
          coverImgA: [
            { required: true, message: '封面图a-竖不能为空', trigger: 'blur' }
          ],
          coverImgB: [
            { required: true, message: '封面图b-横着不能为空', trigger: 'blur' }
          ],
          // audioUrl: [
          //   { required: true, message: '为音频故事时:音频url不能为空', trigger: 'blur' }
          // ],
          uploadStatus: [
            { required: true, message: '上传状态（-1上传失败，0处理中，1上传成功）不能为空', trigger: 'blur' }
          ],
          status: [
            { required: true, message: '上下架状态(1上架,0下架,-1级联下架)不能为空', trigger: 'blur' }
          ],
          remark: [
            { required: true, message: '备注不能为空', trigger: 'blur' }
          ],
          cornerIdP2: [
            { required: true, message: 'p2位置图标不能为空', trigger: 'blur' }
          ],
          cornerIdP3: [
            { required: true, message: 'p3位置图标不能为空', trigger: 'blur' }
          ],
          cornerIdP4: [
            { required: true, message: 'p4位置图标不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      init (id, audioId) {
        this.progress = 0
        this.dataForm.id = id || 0
        this.dataForm.audioId = audioId
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          this.coverImgErrorTip = ''
          this.bannerImgErrorTip = ''
          this.dataForm.coverImgA=""
          this.dataForm.coverImgB=""
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/audio/pbaaudioitem/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm = data.data.pbaAudioItem
                // this.dataForm.audioId = data.pbaaudioitem.audioId
                // this.dataForm.audioCode = data.pbaaudioitem.audioCode
                // this.dataForm.showType = data.pbaaudioitem.showType
                // this.dataForm.orders = data.pbaaudioitem.orders
                // this.dataForm.itemName = data.pbaaudioitem.itemName
                // this.dataForm.coverImgA = data.pbaaudioitem.coverImgA
                // this.dataForm.coverImgB = data.pbaaudioitem.coverImgB
                // this.dataForm.audioUrl = data.pbaaudioitem.audioUrl
                // this.dataForm.uploadStatus = data.pbaaudioitem.uploadStatus
                // this.dataForm.status = data.pbaaudioitem.status
                // this.dataForm.remark = data.pbaaudioitem.remark
                // this.dataForm.cornerIdP2 = data.pbaaudioitem.cornerIdP2
                // this.dataForm.cornerIdP3 = data.pbaaudioitem.cornerIdP3
                // this.dataForm.cornerIdP4 = data.pbaaudioitem.cornerIdP4
              }
            })
          }
        })
      },
      //音频类型下拉框查询
      // getContentTypeList () {
      //   this.$http({
      //     // url: this.$http.adornUrl(`/picbook/bookcategory/comboBox`),
      //     url: this.$http.adornUrl(`/picbook/combobox/audio/listCategory`),
      //     method: 'post',
      //     params: this.$http.adornParams()
      //   }).then(({data}) => {
      //     if (data && data.code === 0) {
      //       this.showTypeOptions = data.data
      //     }
      //   })
      // },
      // 表单提交
      dataFormSubmit () {
        if (!this.dataForm.coverImgA) {
          this.coverImgErrorTip = '请上传封面图'
        }
        if (!this.dataForm.coverImgB) {
          this.bannerImgErrorTip = '请上传轮播图'
        }
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/audio/pbaaudioitem/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                pbaAudioItem: this.dataForm
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  // duration: 1500,
                  duration: 500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      handleCoverImgSuccess (res, file) {
        // this.dataForm.coverImg = URL.createObjectURL(file.raw)
        this.dataForm.coverImgA = res.url
        let _this = this
        setTimeout(function () {
          _this.$refs.uploadCoverImg.clearFiles()
        }, 1000)
      },
      beforeCoverImgUpload (file) {
        this.coverImgErrorTip = ''
        if (file.type.indexOf('image') < 0) {
          this.coverImgErrorTip = '图片格式不正确'
          return false
        }
      },
      handleCoverImgError (err, file, fileList) {
        this.coverImgErrorTip = '上传失败'
      },
      handleBannerImgSuccess (res, file) {
        // this.dataForm.bannerImg = URL.createObjectURL(file.raw)
        this.dataForm.coverImgB = res.url
        let _this = this
        setTimeout(function () {
          _this.$refs.uploadBannerImg.clearFiles()
        }, 1000)
      },
      beforeBannerImgUpload (file) {
        this.bannerImgErrorTip = ''
        if (file.type.indexOf('image') < 0) {
          this.bannerImgErrorTip = '图片格式不正确'
          return false
        }
      },
      handleBannerImgError (err, file, fileList) {
        this.bannerImgErrorTip = '上传失败'
      },
      previewPicBook () {
        let _this = this
        _this.$emit('previewPicBook', _this.dataForm)
      },
      uploadProgress (p) {
        this.progress = Math.floor(p * 100)
      },
      /**
       * @description [fnUploadRequest 覆盖默认的上传行为，实现自定义上传]
       * @param    {object}   option [上传选项]
       * @return   {null}   [没有返回]
       */
      async fnUploadRequest (option) {
        oss.ossUploadFile(option, this.uploadProgress)
      },
      // apk上传之前
      beforeUploadMp3 (file) {
        // if (file.type.indexOf('application/vnd.android.package-archive') < 0) {
        //   this.$message.error('apk格式不正确')
        //   return false
        // }
        let name = file.name
        // 字符串截取为了兼容火狐，火狐浏览器获取apk文件的type为空
        var mp3 = name.substring(name.length - 3, name.length)
        const isMp3 = mp3 === 'mp3' || 'm4a'
        if (!isMp3) {
          this.$message.error('上传只能是 mp3或者m4a 格式的音频文件!')
        }
        return isMp3
      },
      // //apk上传成功后
      // handleApkSuccess (response, file, fileList) {
      //   this.dataForm.apkUrl = file.url
      //   this.$message.success('上传成功')
      // },
      // 添加多个文件事件
      beyondFile (files, fileList) {
        this.$message({
          message: '一次只能上传一个mp3文件，请删除重新上传',
          type: 'success'
        })
      },
      // 上传mp3文件
      handleMp3Success (response, file, fileList) {
        if (response == null) {
          return
        }
        let retUrl = response.res.requestUrls[0].split('?')[0]
        if (retUrl) {
          if (window.SITE_CONFIG['baseUrl'] == 'https://xxx-app-api.xxx.cn') {
            this.dataForm.audioUrl = retUrl.replace('https://xxx-edu-epxxx.oss-cn-hangzhou.aliyuncs.com', 'http://huiben-oss-cdn.xxx.cn')
          } else {
            this.dataForm.audioUrl = retUrl
          }
          this.$message.success('上传成功')
        }
      },
      // 上传失败
      handleUploadError (err, file, fileList) {
        this.$message.error('上传失败')
      }
    }
  }
</script>
<style scoped lang="less">
  .item-wrapper {
    border: 1px solid #ddd;
    padding: 12px;
    border-radius: 4px;
    margin-bottom: 12px;
    width: 100%;
    .price-item-wrapper {
      display: flex;
      flex-direction: row;
      align-items: center;
      .el-form-item__content {
        float: left;
      }
      .price-input {
        width: 120px;
        margin-left: 10px;
        height: 36px;
        line-height: 36px;
        border-radius: 4px;
        -webkit-appearance: none;
        border: 1px solid #dcdfe6;
        color: #606266;
        padding: 0 15px;
      }
    }
    .item-pic-wrapper {
      display: inline-block;
      .pic {
        display: flex;
        flex-direction: row;
        align-items: center;
        margin-right: 20px;
      }
      .avatar-uploader .el-upload {
        border: 1px solid #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
      }

      .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
      }
      .coverImg-wrapper {
        .coverImg-uploader-icon {
          font-size: 28px;
          color: #8c939d;
          border: 1px solid #d9d9d9;
          border-radius: 6px;
          width: 125px;
          height: 150px;
          line-height: 150px;
          text-align: center;
        }
        .coverImg {
          width: 125px;
          height: 150px;
          display: block;
        }
      }
      .bannerImg-wrapper {
        .bannerImg-uploader-icon {
          font-size: 28px;
          color: #8c939d;
          border: 1px solid #d9d9d9;
          border-radius: 6px;
          width: 266px;
          height: 150px;
          line-height: 150px;
          text-align: center;
        }
        .bannerImg {
          width: 266px;
          height: 150px;
          display: block;
        }
      }
    }
  }

  .el-form-item {
    margin-bottom: 18px;
  }

  .no-bottom-maring.el-form-item {
    margin-bottom: 0px;
  }

  .error-tip {
    color: #f56c6c;
    font-size: 12px;
    line-height: 1;
    padding-top: 4px;
  }

  /** 去除input输入框样式 */
  input[type=number]::-webkit-inner-spin-button {
    -webkit-appearance: none;
  }
</style>